import {useAccountStore} from "./AccountStore.ts";
import {defineStore} from "pinia";
import type {TopicDetailData} from "../network/types/TopicDetail.ts";
import {CacheMap, useCache} from "../utils/CacheUtils.ts";
import type {NgaLocation} from "../network/types/NgaLocation.ts";
import type {ReplyInfo} from "../network/types/Reply.ts";
import {useUserStore} from "./UserStore.ts";

const api = () => useAccountStore().getNgaApi().read

// 检查回复是否应被屏蔽
const checkBlocked = (reply: ReplyInfo) => {
    const userStore = useUserStore();
    const {keywords, users} = userStore.blockConfig
    const hasKeyword = keywords.some(it => reply.title?.includes(it) || reply.content?.includes(it))
    const hasUser = users.some(it => reply.authorUid == it.userId)
    reply.blocked = hasKeyword || hasUser
}

export const useTopicReadStore = defineStore('TopicReadStore', {
    state: () => ({
        cache: new CacheMap<TopicDetailData>(),
        cacheTo: new CacheMap<NgaLocation>(),
    }),
    actions: {
        async readTopic(tid: number, page?: number | 'e' | undefined, authorId?: number | undefined, force?: boolean,): Promise<TopicDetailData> {
            const key = `detail ${tid} ${page} ${authorId}`
            return useCache(this.cache, key, force || page == 'e' || false, () => api().readTopic(tid, page, authorId)).then(res => {
                res.replies.forEach(reply => checkBlocked(reply))
                return res
            })
        },
        async readTopicHtml(tid: number, page?: number | 'e' | undefined, authorId?: number | undefined, force?: boolean,): Promise<TopicDetailData> {
            const key = `detailHtml ${tid} ${page} ${authorId}`
            return useCache(this.cache, key, force || page == 'e' || false, () => api().readTopicHtml(tid, page, authorId)).then(res => {
                res.replies.forEach(reply => checkBlocked(reply))
                return res
            })

        },
        toReply(pid: number): Promise<NgaLocation> {
            const key = `to ${pid}`
            return useCache(this.cacheTo, key, false, () => api().toReply(pid))
        },
        readReply(pid: number, force?: boolean,): Promise<TopicDetailData> {
            const key = `reply ${pid}`
            return useCache(this.cache, key, force || false, () => api().readReply(pid))
        },
        readAnonymous(tid: number, pid: number, page?: number | 'e' | undefined, force?: boolean,): Promise<TopicDetailData> {
            const key = `anonymous ${tid} ${pid} ${page}`
            return useCache(this.cache, key, force || false, () => api().readAnonymous(tid, pid, page))
        },
        vote(tid: number, data: number[]) {
            return api().vote(tid, data)
        },
        report(tid: number, pid?: number | undefined, reason?: string | undefined) {
            return api().report(tid, pid, reason)
        }
    },
})